package com.axjy.myspringdata.service.impl;

import com.axjy.myspringdata.dao.EmpDao;
import com.axjy.myspringdata.pojo.Emp;
import com.axjy.myspringdata.service.EmpService;
import com.axjy.myspringdata.util.PageModel;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service("empService")
@Transactional
public class EmpServiceImpl implements EmpService{
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
  private EmpDao empDao;


    @Override
    public void add(Emp emp) {
        empDao.save(emp);
    }

    @Override
    public void del(Integer id) {
        empDao.delete(id);
    }

    @Override
    public void update(Emp emp) {
        entityManager.merge(emp);
    }

    @Override
    public List<Emp> searchAll(String ename) {
        if(StringUtils.isEmpty(ename)){
            return empDao.findAll();
        }
        return empDao.findEmpsByEnameContains(ename);
    }

    @Override
    public Emp get(Integer id) {
        return empDao.findOne(id);
    }

    @Override
    public PageModel searchPager(Integer offset, Integer pageSize) {
        PageModel pm=new PageModel();
        Pageable pageable=new PageRequest(offset/pageSize,pageSize);
        Page<Emp> page=empDao.findAll(pageable);
        pm.setRows(page.getContent());
        pm.setTotal(page.getTotalElements());
        return pm;
    }

    @Override
    public PageModel searchPager(Integer offset, Integer pageSize, String ename) {
        PageModel pm=new PageModel();
        Pageable pageable=new PageRequest(offset/pageSize,pageSize);
        Page<Emp> page=empDao.findByEname("%"+ename+"%",pageable);
        pm.setRows(page.getContent());
        pm.setTotal(page.getTotalElements());
        return pm;
    }
}
